<template>
  <div class="pledge-container">
    <div class="banner">
      <span class="p1">Pledge Amount</span><br />
      <span class="p2">{{ integral }}</span>
    </div>
    <div class="content">
      <div class="left-content flex-box">
        <div class="left-content-header">
          <span>ZTC Staking</span>
          <p>Use Asset (ZTC) Earn ZTC</p>
        </div>
        <div class="left-content-subject">
          <div class="box-list">
            <div class="box-list-flex">
              <div class="h5">APY</div>
              <div class="p">1,036%</div>
            </div>
            <div class="box-list-flex">
              <div class="h5">Staking currency</div>
              <div class="currency-button">
                <button type="button" class="btn btn-primary" data-bs-toggle="dropdown" aria-expanded="false">
                  <div class="button-logo">
                    <img :src="currentPledgeLogo" alt="" />
                  </div>
                  <div class="button-tile">
                    <p class="coin-name">{{ crrentPledgeCoinName }}</p>
                    <p class="blacklink">{{ crrentPledgeNode }}</p>
                  </div>
                  <i class="bi bi-chevron-down"></i>
                </button>
                <ul class="dropdown-menu">
                  <li class="li-one" @click="getTakeObject('image1', 'BTC', 'BTC')">
                    <a class="dropdown-item" href="#">
                      <img class="li-iocn" src="@/assets/img/bteyuanlogo.png" alt="" />
                      <div class="li-iocn-des">
                        <p class="span2">BTC</p>
                        <p class="span3">BTC</p>
                      </div>
                    </a>
                  </li>
                  <hr />
                  <li @click="getTakeObject('image2', 'ETH', 'ETH')">
                    <a class="dropdown-item" href="#">
                      <img class="li-iocn" src="@/assets/img/ethxiao.png" alt="" />
                      <div class="li-iocn-des">
                        <p class="span2">ETH</p>
                        <p class="span3">ETH</p>
                      </div>
                    </a>
                  </li>
                  <hr />
                  <li @click="getTakeObject('image3', 'USDT', 'USDT')">
                    <a class="dropdown-item" href="#">
                      <img class="li-iocn" src="@/assets/img/usdtxiao.png" alt="" />
                      <div class="li-iocn-des">
                        <p class="span2">USDT</p>
                        <p class="span3">USDT</p>
                      </div>
                    </a>
                  </li>
                  <hr />
                  <li class="li-wu" @click="getTakeObject('image4', 'BNB', 'BNB')">
                    <a class="dropdown-item" href="#">
                      <img class="li-iocn" src="@/assets/img/BNBXIAO.png" alt="" />
                      <div class="li-iocn-des">
                        <p class="span2">BNB</p>
                        <p class="span3">BNB</p>
                      </div>
                    </a>
                  </li>
                  <!-- <hr> -->
                  <!-- <li class="li-wu" @click="getTakeObject('image5','ZTC','ZTC')"><a class="dropdown-item" href="#">
                                            <img class="li-iocn" src="@/assets/img/yuanlog.png" alt="">
                                            <div class="li-iocn-des">
                                                <p class="span2">ZTC</p>
                                                <p class="span3">ZTC</p>
                                            </div>
                                            </a>
                                         </li> -->
                </ul>
              </div>
            </div>

            <div class="box-list-flex">
              <div class="h5">Staking num</div>
              <div>
                <input class="input-text" type="text" v-model="stakingNum"
                  placeholder="Please enter the receiving address" />
                <p class="f1 input-p">
                  ETH (ZTC) balance:
                  <img :src="currentPledgeLogo" alt="" /><span class="f2 balance">{{tokenBalance}}</span>
                </p>
              </div>
            </div>

            <div class="box-list-flex">
              <div class="h5">Pledge time</div>
              <div class="box-list-flex-button">
                <button class="pledge-time-button" @click="getDays(30)" :style="{
        backgroundColor:
          stakingDays == 30
            ? 'rgb(255, 141, 26)'
            : 'rgb(128, 128, 128)',
      }">
                  30 D
                </button>
                <button class="pledge-time-button" @click="getDays(90)" :style="{
        backgroundColor:
          stakingDays == 90
            ? 'rgb(255, 141, 26)'
            : 'rgb(128, 128, 128)',
      }">
                  90 D
                </button>
                <button class="pledge-time-button" @click="getDays(180)" :style="{
        backgroundColor:
          stakingDays == 180
            ? 'rgb(255, 141, 26)'
            : 'rgb(128, 128, 128)',
      }">
                  180 D
                </button>
                <button class="pledge-time-button" @click="getDays(360)" :style="{
        backgroundColor:
          stakingDays == 360
            ? 'rgb(255, 141, 26)'
            : 'rgb(128, 128, 128)',
      }">
                  360 D
                </button>
              </div>
            </div>

            <div class="box-list-flex">
              <div class="h5">Estimated revenue:</div>
              <div class="estimated-pec-div">
                <span class="estimated-pec">4135.26</span>
                <img class="estimated-yuanlog" src="@/assets/img/yuanlog.png" alt="" />
                <span class="coin-name">ZTC（30%）</span>
              </div>
            </div>
          </div>
          <button class="confirm-button" @click="sendTransaction">
            Confirm
          </button>
        </div>
      </div>
      <div class="right-content flex-box">
        <div class="right-content-title">Pledge Record</div>
        <div class="right-content-body">
          <div class="right-content-card">
            <div class="right-content-card-list">
              <div class="days">2024/03/28</div>
              <div></div>
            </div>
            <div class="right-content-card-list">
              <div class="f1 card-title">Num</div>
              <div class="f1">Output</div>
            </div>
            <div class="right-content-card-list">
              <div class="f1 card-coin-name">
                <span class="f3">2.3658</span><img class="xiaologo" src="@/assets/img/ethxiaotubiao.png" alt="" />
                ETH
              </div>
              <div class="f1">
                <span class="f3">56583.4</span><img class="xiaologo" src="@/assets/img/yuanlog.png" alt="" />
                ZTC
              </div>
            </div>
            <div class="right-content-card-list">
              <div>
                <span class="f1">Time</span>
                <p class="f1"><span class="f3">180</span> Day</p>
              </div>
              <div class="card-button"><button>Unpledge</button></div>
            </div>
          </div>
          <div class="right-content-card">
            <div class="right-content-card-list">
              <div class="days">2024/03/28</div>
              <div></div>
            </div>
            <div class="right-content-card-list">
              <div class="f1 card-title">Num</div>
              <div class="f1">Output</div>
            </div>
            <div class="right-content-card-list">
              <div class="f1 card-coin-name">
                <span class="f3">2.3658</span><img class="xiaologo" src="@/assets/img/ethxiaotubiao.png" alt="" />
                ETH
              </div>
              <div class="f1">
                <span class="f3">56583.4</span><img class="xiaologo" src="@/assets/img/yuanlog.png" alt="" />
                ZTC
              </div>
            </div>
            <div class="right-content-card-list">
              <div>
                <span class="f1">Time</span>
                <p class="f1"><span class="f3">180</span> Day</p>
              </div>
              <div class="card-button"><button>Unpledge</button></div>
            </div>
          </div>
          <div class="right-content-card">
            <div class="right-content-card-list">
              <div class="days">2024/03/28</div>
              <div></div>
            </div>
            <div class="right-content-card-list">
              <div class="f1 card-title">Num</div>
              <div class="f1">Output</div>
            </div>
            <div class="right-content-card-list">
              <div class="f1 card-coin-name">
                <span class="f3">2.3658</span><img class="xiaologo" src="@/assets/img/ethxiaotubiao.png" alt="" />
                ETH
              </div>
              <div class="f1">
                <span class="f3">56583.4</span><img class="xiaologo" src="@/assets/img/yuanlog.png" alt="" />
                ZTC
              </div>
            </div>
            <div class="right-content-card-list">
              <div>
                <span class="f1">Time</span>
                <p class="f1"><span class="f3">180</span> Day</p>
              </div>
              <div class="card-button"><button>Unpledge</button></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-button v-if="false" :plain="true"></el-button>
  </div>
</template>
<script>
import { Button, Message } from 'element-ui'
import Web3 from 'web3'
import { payCoinOrder, getZtcPledgeIntegral, getAverAddress } from '@/api/pledge.js'
export default {
  components: {
    Message,
    Web3,
    Button
  },
  data () {
    return {
      images: {
        image1: require('@/assets/img/bteyuanlogo.png'),
        image2: require('@/assets/img/ethxiao.png'),
        image3: require('@/assets/img/usdtxiao.png'),
        image4: require('@/assets/img/BNBXIAO.png'),
        image5: require('@/assets/img/yuanlog.png')
      },
      currentPledgeLogo: require('@/assets/img/bnb.png'),
      crrentPledgeCoinName: 'BNB',
      crrentPledgeNode: 'bsc',
      stakingNum: 0,
      stakingDays: '30',
      web3: null,
      accounts: 'initialValue',
      ethChainId: '0x1',
      hash: '',
      overAddress: '',
      integral: 0,
      tokenBalance: 0
    }
  },
  methods: {
    async addPledgeOrder () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      const res = await payCoinOrder({
        hash: this.hash, // 每页10条
        coinName: this.crrentPledgeCoinName,
        userAddress: this.accounts,
        amount: this.stakingNum,
        overAddress: this.overAddress
      })
      this.blockArray = res.data.blockInfo
    },
    // 获取积分
    async getPledgeIntegral () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      const res = await getZtcPledgeIntegral({
        address: this.accounts
      })
      this.integral = res.result
    },
    // 获取收款地址
    async getAverAdr () {
      const res = await getAverAddress({})
      this.overAddress = res.result
    },

    getTakeObject (str1, str2, str3) {
      this.currentPledgeLogo = this.images[str1]
      this.crrentPledgeCoinName = str2
      this.crrentPledgeNode = str3
    },
    getDays (days) {
      this.stakingDays = days
    },

    // 提示框
    open (meg) {
      this.$message(meg)
    },

    // 小狐狸授权
    async loadWeb3 () {
      if (window.ethereum) {
        if (window.ethereum) {
          await window.ethereum.enable().then((res) => {
            this.accounts = res[0]
            this.open(res[0])
          })
        } else {
          this.open(
            'MetaMask is not installed. Please consider installing it: https://metamask.io/download.html'
          )
        }
      }
    },

    // 调起转账
    async sendTransaction () {
      // ETH操作
      if (this.crrentPledgeCoinName === 'ETH') {
        this.getEthTransfer()
      }
      // BNB操作
      if (this.crrentPledgeCoinName === 'BNB') {
        this.getBnbTransfer()
      }
      // 转账usdt
      if (this.crrentPledgeCoinName === 'USDT') {
        this.transferUSDT()
      }
      // 转账BTC
      if (this.crrentPledgeCoinName === 'BTC') {
        this.unisatTran()
      }
    },

    // 切换ETH主网
    switchEthMainnet () {
      if (window.ethereum) {
        try {
          window.ethereum.request({
            method: 'wallet_switchEthereumChain',
            params: [{ chainId: this.ethChainId }]
          })
        } catch (error) {
          console.error(error)
        }
      }
    },
    // 切换BNB主网
    switchToBinanceMainnet () {
      if (window.ethereum) {
        const bscChainData = {
          chainId: '0x38', // 56 in decimal
          chainName: 'Binance Smart Chain Mainnet',
          nativeCurrency: {
            name: 'BNB',
            symbol: 'BNB',
            decimals: 18
          },
          rpcUrls: ['https://bsc-dataseed.binance.org/'],
          blockExplorerUrls: ['https://bscscan.com']
        }

        // MetaMask requires requesting permission to add a new network
        try {
          window.ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [bscChainData]
          })
        } catch (addError) {
          console.error('Error adding Binance Smart Chain to MetaMask', addError)
        }

        try {
          window.ethereum.request({
            method: 'wallet_switchEthereumChain',
            params: [{ chainId: '0x38' }] // BNB主网的链ID是56，0x38是其十六进制表示
          })
        } catch (error) {
          // 处理错误，例如用户拒绝切换网络
          console.log(error)
        }
      } else {
        // 如果window.ethereum不可用，提示用户
        console.log('MetaMask或其他Web3钱包未安装')
      }
    },

    // ETH转账
    async getEthTransfer () {
      const networkId = await window.ethereum.request({
        method: 'net_version'
      })
      // ETH主网络的ID "1"   如果不是主网就切换到主网
      if (networkId !== '1') {
        this.switchEthMainnet()
      }
      // 取第一个账户
      const accounts = await window.ethereum.request({
        method: 'eth_requestAccounts'
      })
      const account = accounts[0]
      this.accounts = account
      // 获取余额
      const balanceWei = await window.ethereum.request({
        method: 'eth_getBalance',
        params: [account, 'latest']
      })
      // 转换余额为Ether
      const balance = parseInt(balanceWei, 16) / 1e18
      this.balance = balance.toFixed(4) // 保留4位小数
      this.tokenBalance = balance
      if (balance > this.stakingNum) {
        web3 = new Web3(window.ethereum)
        const transactionObject = {
          from: this.accounts,
          to: this.overAddress,
          value: this.stakingNum * Math.pow(10, 18)
        }
        const receipt = await web3.eth.sendTransaction({
          ...transactionObject,
          gas: await web3.eth.estimateGas(transactionObject),
          gasPrice: await web3.eth.getGasPrice()
        })
        this.hash = receipt.transactionHash
        console.log('交易hash：', receipt.transactionHash)
      } else {
        this.open('Insufficient balance')
      }
    },

    // BNB转账
    async getBnbTransfer () {
      const web3 = new Web3(window.ethereum)
      try {
        // 确保web3连接到BSC网络   获取网络id 如果不是主网就切换
        const chainId = await window.ethereum.request({
          method: 'eth_chainId'
        })
        if (chainId !== '0x38') {
          this.switchToBinanceMainnet()
        }
        // 请求用户授权
        const accounts = await window.ethereum.request({
          method: 'eth_requestAccounts'
        })
        const account = accounts[0] // 选择第一个账户
        this.accounts = account
        // 获取余额
        const balanceWei = await window.ethereum.request({
          method: 'eth_getBalance',
          params: [account, 'latest']
        })
        this.tokenBalance = balanceWei
        if (balanceWei > this.stakingNum) {
          // 用户的MetaMask账户地址
          const fromAddress = this.accounts
          // 收款方地址
          const toAddress = this.overAddress
          // 转账金额
          const value = this.stakingNum * Math.pow(10, 18)
          // 构造交易对象
          const transactionObject = {
            from: fromAddress,
            to: toAddress,
            value: value
          }
          // 估算gas
          const gas = await web3.eth.estimateGas(transactionObject)
          const gasPrice = await web3.eth.getGasPrice()
          // 发起交易
          const receipt = await web3.eth.sendTransaction({
            ...transactionObject,
            gas: gas,
            gasPrice: gasPrice
          })
          // 输出交易hash
          this.hash = receipt.transactionHash
          console.log('交易hash：', receipt.transactionHash)
        } else {
          this.open('Insufficient balance')
        }
      } catch (error) {
        console.error('错误：' + error.message)
      }
    },
    // 转账USDT
    async transferUSDT () {
      const web3 = new Web3(window.ethereum)
      if (!web3) {
        return
      }
      const usdtContractAddress = '0xf5cac596d46efa574a5c47d49abe633ed2831ec7' // USDT合约地址
      const usdtABI = [
        {
          constant: false,
          inputs: [
            {
              name: '_to',
              type: 'address'
            },
            {
              name: '_value',
              type: 'uint256'
            }
          ],
          name: 'transfer',
          outputs: [
            {
              name: '',
              type: 'bool'
            }
          ],
          type: 'function',
          payable: false,
          stateMutability: 'nonpayable'
        }
        // ,
        // // balanceOf 方法的 ABI
        // {
        //   constant: true,
        //   inputs: [{ name: '_owner', type: 'address' }],
        //   name: 'balanceOf',
        //   outputs: [{ name: 'balance', type: 'uint256' }],
        //   type: 'function'
        // }
      ]
      // 获取当前用户的第一个账户
      const accounts = await web3.eth.getAccounts()
      const sender = accounts[0]
      const usdtContract = new web3.eth.Contract(usdtABI, usdtContractAddress)
      const decimals = 6 // USDT使用的小数位数

      // usdtContract.methods.balanceOf(sender).call()
      //   .then(balance => {
      //     const formattedBalance = balance / Math.pow(10, decimals) // 将余额转换为正常的USDT数额
      //     console.log(`USDT Balance: ${formattedBalance}`)
      //   })
      //   .catch(err => console.error(err))

      const amountToSend = (this.stakingNum * Math.pow(10, decimals)).toString() // 转换为字符串
      // 调用USDT合约的transfer方法
      usdtContract.methods
        .transfer(this.overAddress, amountToSend)
        .send({ from: sender })
        .on('transactionHash', function (hash) {
          console.log('Transaction hash: ', hash)
          this.hash = hash
        })
        .on('receipt', function (receipt) {
          console.log('Receipt: ', receipt)
        })
        .on('error', console.error) // 如果交易出错，控制台打印错误
    }
  },
  created () {
    this.getAverAdr()
  },
  mounted () {
    document.body.style.backgroundColor = 'black'
    this.loadWeb3()
  },
  watch: {
    accounts (newVal, oldVal) {
      this.getPledgeIntegral(newVal)
    }
  }
}
</script>
<style scoped lang="less">
@import "@/assets/css/pledge/pledge-min992.less";
@import "@/assets/css/pledge/pledge-min768.less";
@import "@/assets/css/pledge/pledge-max768.less";
</style>
